package com.example.validator;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.anno.UserNameExistValidAnno;
import com.example.domain.SysUser;
import com.example.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

//@Scope("prototype")
@Component
public class UserNameExistValidator implements ConstraintValidator<UserNameExistValidAnno, String> {

    @Autowired
    SysUserService sysUserService;

    @Override
    public void initialize(UserNameExistValidAnno constraintAnnotation) {
    }

    @Override
    public boolean isValid(String curUserName, ConstraintValidatorContext context) {
        LambdaQueryWrapper<SysUser> q = new LambdaQueryWrapper<>();
        q.eq(SysUser::getUserName, curUserName);
        long count = sysUserService.getBaseMapper().selectCount(q);
        return count == 0L;
    }
}
